package own.stu.jobgib.playown.netty.teston;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;
import io.netty.util.concurrent.DefaultThreadFactory;
import io.netty.util.concurrent.ThreadPerTaskExecutor;
import lombok.extern.slf4j.Slf4j;
import org.asynchttpclient.netty.util.ByteBufUtils;

import java.nio.charset.Charset;

@Slf4j
public class Client {

    static final String HOST = System.getProperty("host", "127.0.0.1");
    static final int PORT = Integer.parseInt(System.getProperty("port", "8888"));
    private static int maxContentLength = 8 * 1024 * 1024;

    public static void main(String[] args) {
        EventLoopGroup group = new NioEventLoopGroup(1, new ThreadPerTaskExecutor(new DefaultThreadFactory("client")));
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline().addLast(new HttpClientCodec());
                        ch.pipeline().addLast(new HttpObjectAggregator(Short.MAX_VALUE));
                        ch.pipeline().addLast(
                                new HttpServerExpectContinueHandler(),
                                new HttpClientHandler());
                    }
                });

        try {
            for (int i = 0; i < 400; i++) {
                ChannelFuture channelFuture = bootstrap.connect(HOST, PORT).sync();
                // error code
                /*channelFuture.channel().closeFuture().addListener((r) -> {
                    group.shutdownGracefully();
                });*/

                channelFuture.channel().closeFuture().sync().addListener(r -> {
                    log.info("close channel");
                });
            }

            // group.shutdownGracefully(5L, 10, TimeUnit.SECONDS);

            Runtime.getRuntime().addShutdownHook(new Thread(() -> {
                group.shutdownGracefully();
            }, "client - hook"));
        } catch (InterruptedException e) {
            log.error("client : ", e);
        }
    }

    public static class HttpClientHandler extends SimpleChannelInboundHandler<FullHttpResponse> {

        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {

            ByteBuf body = Unpooled.wrappedBuffer("Http message!".getBytes("UTF-8"));
            DefaultFullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
                    "/user?id=10&addr=NanJing", body);

            ctx.channel().writeAndFlush(request);
        }

        @Override
        protected void channelRead0(ChannelHandlerContext ctx, FullHttpResponse msg) throws Exception {
            if (msg.decoderResult().isFailure())
                throw new Exception("Decode HttpResponse error : " + msg.decoderResult().cause());

            log.info("get from server : {}", ByteBufUtils.byteBuf2String(Charset.defaultCharset(), msg.content()));
            ctx.close();
        }

        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            ctx.close();
        }
    }
}
